package com.example.foo.api.web.account;

import java.util.Objects;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.ruoyi.common.core.domain.AjaxResult;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.account.model.AccountItem;
import com.example.foo.account.query.AccountItemQuery;
import com.example.foo.account.service.AccountService;
import com.example.foo.api.boot.TokenHelper;

@org.springframework.web.bind.annotation.RestController
public class AccountItemAction {

	private final AccountService accountService;

	public AccountItemAction(AccountService accountService) {
		this.accountService = accountService;
	}

	@GetMapping("/api/accountitems")
	public AjaxResult index(AccountItemQuery accountItemQuery, Pageable pageable) {
		Long userId = TokenHelper.verifyToken();
		if (!Objects.equals(userId, accountItemQuery.getUserId())) {
			return AjaxResult.error(403, "Access Forbidden");
		}
		PageResult<AccountItem> pageResult = accountService.findAccountItems(accountItemQuery, pageable);
		return AjaxResult.successData(pageResult);
	}

	@GetMapping("/api/accountitems/{id}")
	public AjaxResult showAccountItem(@PathVariable("id") Long id) {
		Long userId = TokenHelper.verifyToken();
		AccountItem accountItem = accountService.findAccountItemById(id);
		if (accountItem == null) {
			return AjaxResult.error(404, "Not Found");
		}
		if (!Objects.equals(userId, accountItem.getUserId())) {
			return AjaxResult.error(403, "Access Forbidden");
		}
		return AjaxResult.successData(accountItem);
	}

}
